/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ProdutoDialog.java
 *
 * Created on Jan 14, 2011, 10:38:02 AM
 */
package br.com.tbp.gui;

import br.com.tbp.controle.ControleProduto;
import br.com.tbp.exception.InputValidationException;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.model.domain.Produto;
import br.com.tbp.model.domain.constant.TipoDeProduto;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Diego Freire
 */
public class ProdutoDialog extends javax.swing.JDialog {

    private boolean novoProduto;
    private Produto produto;
    private boolean refresh = false;

    public ProdutoDialog(java.awt.Frame parent, String name, boolean modal) {
        super(parent, name, modal);
        initComponents();
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        contentPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        msgLabel = new javax.swing.JLabel();
        jPanel10 = new javax.swing.JPanel();
        ativoCheckBox = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        idTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        nomeTextField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        obsTextArea = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        tipoComboBox = new javax.swing.JComboBox();
        jPanel4 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        novoButton = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        salvarButton = new javax.swing.JButton();
        fecharButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        contentPanel.setLayout(new java.awt.BorderLayout());

        jPanel1.setPreferredSize(new java.awt.Dimension(400, 40));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel9.setBackground(new java.awt.Color(255, 255, 255));
        jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        msgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/phone32.png"))); // NOI18N
        msgLabel.setText("msg");
        jPanel9.add(msgLabel);

        jPanel1.add(jPanel9, java.awt.BorderLayout.CENTER);

        jPanel10.setBackground(new java.awt.Color(255, 255, 255));
        jPanel10.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 1, 1, 1));

        ativoCheckBox.setBackground(new java.awt.Color(227, 221, 221));
        ativoCheckBox.setText("Ativo");
        jPanel10.add(ativoCheckBox);

        jPanel1.add(jPanel10, java.awt.BorderLayout.LINE_END);

        contentPanel.add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Info. Básicas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12))); // NOI18N

        jLabel1.setText("ID produto:");

        idTextField.setEditable(false);
        idTextField.setFocusable(false);

        jLabel2.setText("Nome:");

        jLabel3.setText("Observações:");

        obsTextArea.setColumns(20);
        obsTextArea.setLineWrap(true);
        obsTextArea.setRows(5);
        obsTextArea.setWrapStyleWord(true);
        jScrollPane1.setViewportView(obsTextArea);

        jLabel4.setText("Tipo:");

        tipoComboBox.setModel(new DefaultComboBoxModel(TipoDeProduto.values()));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(nomeTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)
                            .addComponent(tipoComboBox, 0, 412, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 503, Short.MAX_VALUE)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(424, 424, 424)))))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(nomeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tipoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        contentPanel.add(jPanel2, java.awt.BorderLayout.CENTER);

        getContentPane().add(contentPanel, java.awt.BorderLayout.CENTER);

        jPanel4.setLayout(new java.awt.BorderLayout());

        novoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/plus_16.png"))); // NOI18N
        novoButton.setMnemonic('n');
        novoButton.setText("Novo Produto");
        novoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                novoButtonActionPerformed(evt);
            }
        });
        jPanel5.add(novoButton);

        jPanel4.add(jPanel5, java.awt.BorderLayout.LINE_START);

        salvarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/salvar.png"))); // NOI18N
        salvarButton.setMnemonic('s');
        salvarButton.setText("Salvar");
        salvarButton.setPreferredSize(new java.awt.Dimension(120, 26));
        salvarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salvarButtonActionPerformed(evt);
            }
        });
        jPanel6.add(salvarButton);

        fecharButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/delete.png"))); // NOI18N
        fecharButton.setText("Fechar (ESC)");
        fecharButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fecharButtonActionPerformed(evt);
            }
        });
        jPanel6.add(fecharButton);

        jPanel4.add(jPanel6, java.awt.BorderLayout.LINE_END);

        getContentPane().add(jPanel4, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void novoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_novoButtonActionPerformed
        setProduto(new Produto());
        setNovoProduto(true);
}//GEN-LAST:event_novoButtonActionPerformed

    private void salvarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarButtonActionPerformed
        try {
            this.validarEntradaDoUsuario();

            ControleProduto controle = new ControleProduto();
            Produto c = this.getProduto();
            if (isNovoProduto()) {
                controle.adicionar(c);
                msgLabel.setText("O produto foi salvo com sucesso");
                refresh(true);
            } else {
                controle.atualizar(c);
                msgLabel.setText("Os dados do produto foram atualizados com sucesso");
                refresh(true);
            }
        } catch (InputValidationException ivex) {
            msgLabel.setText(ivex.getMessage());
            System.out.println(ivex.getMessage());
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
}//GEN-LAST:event_salvarButtonActionPerformed

    private void fecharButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecharButtonActionPerformed
        this.dispose();
}//GEN-LAST:event_fecharButtonActionPerformed

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ProdutoDialog dialog = new ProdutoDialog(new javax.swing.JFrame(), "TBP - Produto", true);
                dialog.setProduto(new Produto());
                dialog.setNovoProduto(true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // <editor-fold defaultstate="collapsed" desc="Declaration of class members">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox ativoCheckBox;
    private javax.swing.JPanel contentPanel;
    private javax.swing.JButton fecharButton;
    private javax.swing.JTextField idTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel msgLabel;
    private javax.swing.JTextField nomeTextField;
    private javax.swing.JButton novoButton;
    private javax.swing.JTextArea obsTextArea;
    private javax.swing.JButton salvarButton;
    private javax.swing.JComboBox tipoComboBox;
    // End of variables declaration//GEN-END:variables
    // </editor-fold>

    public boolean isNovoProduto() {
        return novoProduto;
    }

    public void setNovoProduto(boolean novoProduto) {
        this.novoProduto = novoProduto;
        if (isNovoProduto()) {
            msgLabel.setText("Forneça os dados para o novo produto");
        } else {
            msgLabel.setText("Visualização dos dados do produto " + this.produto.getNome());
        }
        nomeTextField.requestFocus();
    }

    public Produto getProduto() {
        produto.setNome(nomeTextField.getText());
        produto.setTipo((TipoDeProduto) tipoComboBox.getSelectedItem());
        produto.setObservacoes(obsTextArea.getText());
        produto.setAtivo(ativoCheckBox.isSelected());
        return produto;
    }

    public void setProduto(Produto produto) {
        this.produto = produto;

        ativoCheckBox.setSelected(produto.isAtivo());
        //idTextField.setText(produto.getId() > 0 ? "" + produto.getId() : null);
        idTextField.setText(""+produto.getId());
        nomeTextField.setText(produto.getNome());
        tipoComboBox.setSelectedItem(produto.getTipo());
        obsTextArea.setText(produto.getObservacoes());
        obsTextArea.setCaretPosition(0);
    }

    public void validarEntradaDoUsuario() throws InputValidationException {
        if (nomeTextField.getText().isEmpty()) {
            nomeTextField.requestFocus();
            throw new InputValidationException("O nome deve ser informado");
        }
    }

    public boolean refresh() {
        return refresh;
    }

    public void refresh(boolean r) {
        this.refresh = r;
    }

    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                fecharButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
